<template>
  <div class="doctor-selection">
    <!-- 搜索 -->
    <input 
      v-model="lhxSearchKeyword" 
      placeholder="搜索医生..."
      class="search-input"
    />
    
    <!-- 医生列表 -->
    <div v-if="lhxLoading">加载中...</div>
    <div v-else-if="lhxError">{{ lhxError }}</div>
    <div v-else>
      <div v-if="lhxFilteredDoctors.length === 0">暂无医生</div>
      <div 
        v-for="doctor in lhxFilteredDoctors" 
        :key="doctor.userId"
        class="doctor-card"
        @click="lhxSelectDoctor(doctor)"
      >
        <div>
          <strong>{{ doctor.name }}</strong>
          <span>{{ doctor.department }}</span>
        </div>
        <button>{{ doctor.hasExistingChat ? '继续聊天' : '开始聊天' }}</button>
      </div>
    </div>

    <!-- 发起聊天对话框 -->
    <div v-if="lhxShowDialog" class="dialog-overlay" @click="lhxShowDialog = false">
      <div class="dialog" @click.stop>
        <h3>与 {{ lhxSelectedDoctor?.name }} 聊天</h3>
        <textarea 
          v-model="lhxFirstMessage"
          placeholder="请输入消息..."
          class="message-input"
        ></textarea>
        <div class="dialog-actions">
          <button @click="lhxShowDialog = false">取消</button>
          <button @click="lhxStartChat" :disabled="!lhxFirstMessage.trim()">发送</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();

interface Props {
  currentUser: {
    userId: string;
    name: string;
    userType: string;
  };
}

const props = defineProps<Props>();

const lhxLoading = ref(false);
const lhxError = ref('');
const lhxAvailableDoctors = ref<any[]>([]);
const lhxSearchKeyword = ref('');
const lhxShowDialog = ref(false);
const lhxSelectedDoctor = ref<any>(null);
const lhxFirstMessage = ref('');

const lhxFilteredDoctors = computed(() => {
  if (!lhxSearchKeyword.value.trim()) return lhxAvailableDoctors.value;
  const keyword = lhxSearchKeyword.value.toLowerCase();
  return lhxAvailableDoctors.value.filter(d => 
    d.name.toLowerCase().includes(keyword) ||
    d.department.toLowerCase().includes(keyword)
  );
});

async function lhxLoadAvailableDoctors() {
  lhxLoading.value = true;
  try {
    const response = await fetch(`http://localhost:3000/lhx/patient/${props.currentUser.userId}/available-doctors`);
    const result = await response.json();
    if (result.success) {
      lhxAvailableDoctors.value = result.data;
    } else {
      lhxError.value = result.message;
    }
  } catch {
    lhxError.value = '网络错误';
  }
  lhxLoading.value = false;
}

function lhxSelectDoctor(doctor: any) {
  lhxSelectedDoctor.value = doctor;
  if (doctor.hasExistingChat) {
    lhxNavigateToChat(doctor.roomId);
  } else {
    lhxShowDialog.value = true;
  }
}

async function lhxStartChat() {
  if (!lhxSelectedDoctor.value || !lhxFirstMessage.value.trim()) return;
  
  try {
    const response = await fetch(`http://localhost:3000/lhx/patient/${props.currentUser.userId}/start-chat`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        doctorId: lhxSelectedDoctor.value.userId,
        firstMessage: lhxFirstMessage.value.trim()
      })
    });

    const result = await response.json();
    if (result.success) {
      lhxNavigateToChat(result.data.roomId);
    } else {
      alert(`发起聊天失败: ${result.message}`);
    }
  } catch {
    alert('网络错误');
  }
}

function lhxNavigateToChat(roomId: string) {
  lhxShowDialog.value = false;
  router.push({
    path: '/lhx-chat',
    query: {
      lhxRoomId: roomId,
      lhxDoctorId: lhxSelectedDoctor.value.userId,
      lhxDoctorName: lhxSelectedDoctor.value.name,
      lhxUserId: props.currentUser.userId,
      lhxUserType: props.currentUser.userType,
      lhxUserName: props.currentUser.name
    }
  });
}

onMounted(() => {
  lhxLoadAvailableDoctors();
});
</script>

<style scoped>
.doctor-selection {
  padding: 20px;
}

.search-input {
  width: 100%;
  padding: 10px;
  margin-bottom: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.doctor-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #eee;
  margin-bottom: 10px;
  cursor: pointer;
  background: white;
}

.doctor-card:hover {
  background: #f9f9f9;
}

.doctor-card button {
  padding: 8px 16px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 90%;
  max-width: 400px;
}

.message-input {
  width: 100%;
  height: 80px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin: 10px 0;
  resize: vertical;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.dialog-actions button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.dialog-actions button:last-child {
  background: #3498db;
  color: white;
  border-color: #3498db;
}

.dialog-actions button:disabled {
  background: #ccc;
  color: #666;
  cursor: not-allowed;
}
</style>